import ToolActionApi from "@/tool/http/tool-action.js";
import toolArray from "@/tool/tool-array";

let deviceAction = ToolActionApi.init("things_device");
let deviceDataItemAction = ToolActionApi.init("things_device_data_item");
let dataFactorAction = ToolActionApi.init("data_factor");

let metadata = [{ name: "device_code", memo: "设备信息" }];

const rule = {
  queryParams: [],
  metadata: [...metadata],
  async listFieldExtend(list = []) {
    let res = await deviceDataItemAction.list({
      rules: { data_id__in: list.map((item) => item.id).join(",") },
    });

    let tempMetadata = [];

    for (let i = 0; i < list.length; i++) {
      res
        .filter((item) => item.data_id == list[i].id)
        .forEach((dItem) => {
          list[i][`_${dItem.factor_code}`] =
            getVal(dItem.factor_val_cou, "累计") ||
            getVal(dItem.factor_val, "均值") ||
            getVal(dItem.factor_val_rtd, "实时") ||
            getVal(dItem.factor_val_zs_rtd, "折算均值") ||
            dItem.factor_val_zs_avg;
          if (
            !tempMetadata.find(
              (exItem) => exItem.name == `_${dItem.factor_code}`
            )
          ) {
            tempMetadata.push({
              name: `_${dItem.factor_code}`,
              memo: dItem.factor_code,
            });
          }
        });
    }

    // 处理因子名称问题
    let factorList = await dataFactorAction.list({
      rules: { code__in: tempMetadata.map((item) => item.memo) },
    });

    let factorGroup = toolArray.groupBy(factorList, "code");

    tempMetadata.forEach((item) => {
      let factorItems = factorGroup[item.memo];
      if (factorItems && factorItems.length > 0) {
        item.memo = factorItems[0].name;
      }
    });

    return { metadata: tempMetadata, records: list };
  },
};

function getVal(val, name) {
  if (val || val === 0) {
    return name + ":" + val + "";
  }
}

export default async function () {
  rule.metadata[0].dictList = await deviceAction.dict("name", "code");
  return rule;
}
